<template>
  <div>
    <n-grid :x-gap="24">
      <n-grid-item span="6">
        <n-card>
          <n-space justify="end">
            <n-statistic :value="currentSelectNum + 1 ">
              <template #prefix>
                <n-icon @click="preBoard ">
                  <n-el style="color: var(--primary-color)">
                    <ChevronBackCircleSharp/>
                  </n-el>
                </n-icon>
              </template>
              <template #suffix>
                / {{ storyBoardList.length }}
                <n-icon @click="nextBoard">
                  <n-el style="color: var(--primary-color)">
                    <ChevronForwardCircleSharp/>
                  </n-el>
                </n-icon>
              </template>
            </n-statistic>
          </n-space>
          <n-form :model="storyPaintConfig" :rules="rules" ref="formRef">
            <n-form-item label="内容" path="content">
              <n-input v-model:value="storyBoardList[currentSelectNum].content" type="textarea"/>
            </n-form-item>
            <n-form-item label="提示词" path="prompt">
              <n-input v-model:value="storyBoardList[currentSelectNum].prompt" type="textarea"/>
            </n-form-item>
            <n-form-item label="人物" path="characterName">
              <n-input v-model:value="storyBoardList[currentSelectNum].characterName"/>
            </n-form-item>
            <n-form-item label="已有图片">
              <n-grid x-gap="12" :cols="2">
                <n-gi
                    v-for="storyPaintLog in storyBoardList[currentSelectNum].imageList">
                  <n-card style="margin-bottom: 5px;">
                    <template #cover>
                      <div class="image-container-lora"
                           @contextmenu="sendImg(storyPaintLog,$event)"
                      >
                        <n-image :src="fileFunction.getViewFilePathByUserFileId(storyPaintLog)"
                                 class="centered-image-lora"/>
                      </div>
                    </template>
                  </n-card>
                </n-gi>
              </n-grid>
              <n-dropdown
                  placement="bottom-start"
                  trigger="manual"
                  :x="x"
                  :y="y"
                  :options="options"
                  :show="showDropdown"
                  :on-clickoutside="clickOutSide"
                  @select="handleSelect"
              />
            </n-form-item>
          </n-form>
        </n-card>
      </n-grid-item>
      <n-grid-item span="18">
        <stableDiffusionPaint
            v-if="defaultStoryPaintConfig"
            ref="stableDiffusionPaintRef"
            :defaultConfig="defaultStoryPaintConfig"
        />
      </n-grid-item>

    </n-grid>
  </div>
</template>

<script setup lang="ts">
import {computed, nextTick, onMounted, reactive, ref} from 'vue'
import {useMessage} from 'naive-ui'
import {storyController} from '@/api/story/story.api'
import stableDiffusionPaint from '@/views/pages/aiart/stablediffusion/index.vue'
// @ts-ignore
import fileFunction from "@/libs/globalFunction/file"
import {ChevronBackCircleSharp, ChevronForwardCircleSharp} from '@vicons/ionicons5'
import {storyBoardController} from "@/api/controller/story/storyBoard.api";
const loraList = ref([])
const formRef: any = ref(null)
const message = useMessage()
const showDropdown = ref(false)
const x = ref(0)
const y = ref(0)
const stableDiffusionPaintRef = ref(null)
const defaultStoryPaintConfig = ref(null)
const sendImgFileId = ref('')

const props = defineProps({
  storyBoardList: {
    type: Array,
    default: () => {
      return []
    }
  },
  selectNum: {
    type: Number,
    default: () => {
      return {}
    }
  },
  reloadStoryBoards: {
    type: Function,
    default: () => {
      return {}
    }
  }
})

const currentSelectNum = ref(props.selectNum)
// 上一镜
const preBoard = () => {
  if (currentSelectNum.value > 0) {
    currentSelectNum.value = currentSelectNum.value - 1
  }
  getStoryPrompt()
}
// 下一镜
const nextBoard = () => {
  if (currentSelectNum.value < props.storyBoardList.length - 1) {
    currentSelectNum.value = currentSelectNum.value + 1
  }
  getStoryPrompt()
}

// 当前选中的镜
const selectBoard = computed(() => {
  return props.storyBoardList[currentSelectNum.value]
})

const options = [
  {
    label: '发送至图生图',
    key: 'sendToImg2Img'
  },
  {
    label: '发送至ControlNet',
    key: 'sendToControlNet'
  }
]
const clickOutSide = () => {
  showDropdown.value = false
}

const rules = {
  resourceId: {
    required: true,
    message: '请选择资源',
    trigger: 'blur'
  },
  sizeOption: {
    required: true,
    message: '请选择尺寸信息',
    trigger: 'blur'
  },
  defaultModel: {
    required: true,
    message: '请选择模型',
    trigger: 'blur'
  },
  defaultVae: {
    required: true,
    message: '请选择模型',
    trigger: 'blur'
  }
};

// 绘画配置
const storyPaintConfig = ref(reactive({
  paintType: 'SD',
  resourceId: '',
  defaultStyleId: '',
  defaultPrompt: '',
  defaultNegativePrompt: '',
  defaultSeed: -1,
  defaultSamplerName: 'DPM++ 2M',
  defaultBatchSize: 1,
  defaultSteps: 20,
  defaultWidth: 512,
  defaultHeight: 512,
  defaultCfgScale: 7,
  defaultModel: '',
  defaultVae: '',
  sizeOption: '',
  chapterId: selectBoard.value.chapterId,
  defaultVoiceName: '',
  defaultVolume: 1.0,
  defaultRate: 1.0,
  defaultPitch: 1.0,
  voiceType: 'free',
  defaultRestoreFaces: false,
  defaultEnableHr: false,
  defaultHrUpscaler: 'R-ESRGAN 4x+',
  defaultHrScale: 2,
  defaultDenoisingStrength: 0.50,
  defaultHrSecondPassSteps: 8
}))

const handleSelect = (key: string | number) => {
  showDropdown.value = false
  let imgFile = sendImgFileId.value
  if(key == 'sendToImg2Img'){
    stableDiffusionPaintRef.value?.loadImage(imgFile,'img2img')
  }else if(key === 'controlnet'){
    stableDiffusionPaintRef.value?.loadImage(imgFile,'controlnet')
  }
}

const sendImg = (fileId: string, e: MouseEvent) => {
  e.preventDefault()
  sendImgFileId.value = fileId
  nextTick().then(() => {
    showDropdown.value = true
    x.value = e.clientX
    y.value = e.clientY
  })
}

const getStoryPaintConfig = (chapterId: string) => {
  storyController.getStoryPaintConfig(chapterId).then(res => {
    if (res.code === 200) {
      if (res.data != null) {
        defaultStoryPaintConfig.value = JSON.parse(res.data.paintConfigText);
        getStoryPrompt()
      }
    } else {
      message.error(res.msg);
    }
  })
}

const getStoryPrompt = () =>{
  storyBoardController.getStoryBoardPrompt(selectBoard.value.id).then(res => {
    if (res.code === 200) {
      if (res.data != null) {
        nextTick().then(() => {
          stableDiffusionPaintRef.value?.loadPrompt(res.data,selectBoard.value.id);
        })
      }
    } else {
      message.error(res.msg);
    }
  })
}


onMounted(() => {
  getStoryPaintConfig(selectBoard.value.chapterId)
});

</script>
<style>
.image-container-lora {
  height: 150px; /* 设置容器的固定高度 */
  display: flex; /* 使用Flex布局 */
  align-items: center; /* 垂直居中 */
  justify-content: center; /* 水平居中 */
}

.centered-image-lora {
  max-height: 100%; /* 图片的最大高度为容器高度，宽度会自动适应宽高比例 */
  max-width: 100%; /* 图片的最大宽度为容器宽度，高度会自动适应宽高比例 */
}

</style>
